<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend>分类管理</legend>
</fieldset>
<div id="category_tree" class="demo-tree-more"></div>
<script src="layui/layui.all.js" charset="utf-8"></script>
<script src="js/jquery.js"></script>
<script>
    var pid = 0;

    layui.use(['tree'], function () {
        var tree = layui.tree;

        function categoryTree() {
            $.post("?r=admin/category-tree", {}, function (res) {
                tree.render({
                    elem: '#category_tree'
                    , data: res.data
                    , showLine: false  //是否开启连接线
                    , edit: ['add', 'update', 'del']
                    , operate: function (obj) {
                        let type = obj.type; //得到操作类型：add、edit、del
                        let data = obj.data; //得到当前节点的数据
                        let elem = obj.elem; //得到当前节点元素

                        //Ajax 操作
                        let id = data.id; //得到节点索引
                        if (type === 'add') { //增加节点
                            pid = id;
                        } else if (type === 'update') { //修改节点
                            let name = elem.find('.layui-tree-txt').html();
                            if (id === undefined) {//add
                                add(pid, name);
                            } else {
                                edit(id, name);
                            }
                        } else if (type === 'del') { //删除节点
                            del(id);
                        }
                    }
                });
            }, 'json');
        }

        categoryTree();

        //删除分类
        function del(id) {
            $.post("?r=admin/del-category", {id: id}, function (res) {
                if (res.code === 'success') {
                    categoryTree()
                }
            }, 'json')
        }

        //添加分类
        function add(pid, name) {
            $.post("?r=admin/add-category", {pid: pid, name: name}, function (res) {
                if (res.code === 'success') {
                    categoryTree()
                }
            }, 'json')
        }

        function edit(id, name) {
            $.post("?r=admin/edit-category", {id: id, name: name}, function (res) {
                if (res.code === 'success') {
                    categoryTree()
                }
            }, 'json')
        }

    });
</script>
